﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data;
using System.Net;
using System.IO;

namespace orderCreater
{
    class Common
    {
        public static MySqlHelp db = new MySqlHelp(ConfigurationManager.AppSettings["ConnectionString-531"]);
        public static DataRow getRandAccepter(string cityIds, string areaIds)
        {
            string useCountCondition = ConfigurationManager.AppSettings["useCountCondition"];
            DataSet ds = new DataSet();
            string sql = "SELECT * FROM db_v_accepter where city_id in(" + cityIds + ") " + useCountCondition + " and area_id in(" + areaIds + ") and handle_state=20 ORDER BY rand() asc LIMIT 1;";
            ds = db.ExecuteSqlDataSet(sql);
            int count = ds.Tables[0].Rows.Count;
            if (count > 0)
            {
                db.ExecuteSql("update db_v_accepter set useCount=useCount+1 where id=" + ds.Tables[0].Rows[0]["id"].ToString() + ";");
                return ds.Tables[0].Rows[0];
            }
            else
            {
                return null;
            }
        }

        public static string post(string url, string paramsStr)
        {
            try
            {
                //注意提交的编码 这边是需要改变的 这边默认的是Default：系统当前编码
                byte[] postData = Encoding.UTF8.GetBytes(paramsStr);

                // 设置提交的相关参数 
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                Encoding myEncoding = Encoding.UTF8;
                request.Method = "POST";
                request.KeepAlive = false;
                request.AllowAutoRedirect = true;
                request.ContentType = "application/x-www-form-urlencoded";
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR  3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";
                request.ContentLength = postData.Length;

                // 提交请求数据 
                System.IO.Stream outputStream = request.GetRequestStream();
                outputStream.Write(postData, 0, postData.Length);
                outputStream.Close();

                HttpWebResponse response;
                Stream responseStream;
                StreamReader reader;
                string srcString;
                response = request.GetResponse() as HttpWebResponse;
                responseStream = response.GetResponseStream();
                reader = new System.IO.StreamReader(responseStream, Encoding.GetEncoding("UTF-8"));
                srcString = reader.ReadToEnd();
                string result = srcString;   //返回值赋值
                reader.Close();
                return result;
            }
            catch
            {
                return "error";
            }
        }
    }
}
